package com.example.controller;

import cn.hutool.core.date.DateUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.example.bean.*;
import com.example.exception.ServiceException;
import com.example.service.*;
import com.example.until.Result;
import com.example.until.ResultCodeEnum;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.util.List;

/**
 * @title: Course
 * @Author wjf
 * @Date: 2022/9/29 14:34
 * @Version 1.0
 */
@RestController
@CrossOrigin
@Slf4j
@RequestMapping("/return")
public class ReturnController {

    @Autowired
    private ReturnService returnService;

    @Resource
    private BorrowService borrowService;

    @Resource
    private BooksService booksService;

    @Resource
    private HistoryService historyService;


    @GetMapping("/page")
    public Result<IPage<Return>> getAllUser(
            @RequestParam(defaultValue = "1") Integer current,
            @RequestParam(defaultValue = "5") Integer pageSize,
            @RequestParam(defaultValue = "") String bookName,
            @RequestParam(value = "nickName", defaultValue = "") String userName) {
        IPage<Return> page = new Page<>(current, pageSize);
        System.out.println(bookName);
        System.out.println(userName);
        IPage<Return> page1 = returnService.findPage(page, bookName, userName);
        return Result.ok(page1);
    }

    @GetMapping({"/byName/{name}"})
    public Result getUserByName(@PathVariable String name) {
        QueryWrapper<Borrow> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq(StringUtils.isNotBlank(name), "name", name);
        Borrow one = borrowService.getOne(queryWrapper);
        return Result.ok(one);
    }

    @GetMapping("/{id}")
    public Result<Borrow> getCourseById(@PathVariable("id") Integer id) {
        Borrow course = borrowService.getById(id);
        return Result.ok(course);
    }


    @PostMapping("/save")
    public Result<Boolean> saveUser(@RequestBody Return re) {
        boolean save = returnService.save(re);
        return Result.ok(save);
    }

    /**
     * 还书审核   接口
     *
     * @param
     * @return
     */
    @Transactional
    @PutMapping("/update")
    public Result<Boolean> putUser(@RequestBody Return re) {
        try {
            LambdaQueryWrapper<Return> queryWrapper = new LambdaQueryWrapper<>();
            queryWrapper.eq(Return::getBorrowId, re.getBorrowId());
            Integer userId = re.getUserId();
            Integer bookId = re.getBookId();
            QueryWrapper<History> queryWrapper1 = new QueryWrapper<>();
            queryWrapper1.eq("user_id",re.getUserId())
                    .eq("book_id",re.getBookId());
            re.setCheckTime(DateUtil.now());
            re.setStatus(1);
            boolean b = returnService.update(re, queryWrapper);
            if (b) {
                // 审核通过 该书的库存加1
                Books book = booksService.getById(re.getBookId());
                Books books = new Books();
                books.setNum(book.getNum() + 1);
                books.setId(re.getBookId());
                boolean b1 = booksService.updateById(books);
                if (b1) {
                    // 归还书 审核成功 生成历史记录
                    // 先判断是否已经借过一次
                    History one = historyService.getOne(queryWrapper1);
                    if (one == null) {  //没有借过
                        //查return表 查出归还时间
                        Return one1 = returnService.getOne(queryWrapper);
                        History history = new History();
                        history.setBookId(bookId);
                        history.setUserId(userId);
                        history.setBorrowTime(re.getBorrowTime());
                        history.setReturnTime(one1.getReturnTime());
                        history.setNum(1);
                        history.setBorrowId(one1.getBorrowId());
                        historyService.save(history);
                    } else { // 借过  num次数 +1
                        Return one1 = returnService.getOne(queryWrapper);
                        History history = new History();
                        history.setBookId(bookId);
                        history.setUserId(userId);
                        history.setBorrowTime(re.getBorrowTime());
                        history.setReturnTime(one1.getReturnTime());
                        history.setNum(one.getNum() + 1);
                        history.setBorrowId(one1.getBorrowId());
                        historyService.save(history);
                    }
                }
                return Result.ok();
            }
            return Result.ok();
        } catch (Exception e) {
            log.error(e.getMessage());
            throw new ServiceException(ResultCodeEnum.SERVICE_ERROR);
        }
    }

    @PutMapping("/delete")
    public Result deleteUser(@RequestBody Return re) {
        LambdaQueryWrapper<Return> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(Return::getBookId, re.getBookId())
                .eq(Return::getUserId, re.getUserId());
        boolean b = returnService.remove(queryWrapper);  //删除记录
        if (b) {
            return Result.ok();
        }
        return Result.fail();
    }

    @DeleteMapping("/delete/batch/{ids}")
    public Result<Boolean> deleteMoreUser(@PathVariable List<Integer> ids) {
        boolean b = borrowService.removeByIds(ids);
        return Result.ok(b);
    }

}
